<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item :label="$t('common.keywords')" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                :placeholder="$t('user.placeholder')"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item :label="$t('common.dept')" prop="deptId">
              <el-select
                v-model="queryParams.deptId"
                :placeholder="$t('common.all')"
                :no-match-text="$t('common.all')"
                clearable
                class="!w-[100px]"
              >
                <el-option
                  v-for="item in deptOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('common.showStatus')" prop="status">
              <el-select
                v-model="queryParams.userStatus"
                :placeholder="$t('common.all')"
                :no-match-text="$t('common.all')"
                clearable
                class="!w-[100px]"
              >
                <el-option :label="$t('common.status.unEnable')" :value="-1" />
                <el-option :label="$t('common.status.enable')" :value="10" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">
                {{ $t("common.search") }}
              </el-button>
              <el-button icon="refresh" @click="handleResetQuery">
                {{ $t("common.reset") }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <div class="flex-x-between mb-10px">
            <div>
              <el-button
                v-hasPerm="['sys:user:add']"
                type="success"
                icon="plus"
                @click="handleOpenDialog(0, 0)"
              >
                {{ $t("common.add") }}
              </el-button>
              <el-button
                v-hasPerm="'sys:user:delete'"
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete()"
              >
                {{ $t("common.delete") }}
              </el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            stripe
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" align="center" />
            <el-table-column :label="$t('user.username')" prop="userEmail">
              <template #default="scope">
                <div class="ellipsis" :title="scope.row.userEmail">{{ scope.row.userEmail }}</div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('user.fullName')" align="center" prop="userFullName" />
            <el-table-column
              v-if="showDept"
              :label="$t('common.dept')"
              align="center"
              prop="deptId"
            >
              <template #default="scope">
                {{ deptOptionsToName[scope.row.deptId] }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('user.phone')" align="center" prop="userPhone" />
            <el-table-column :label="$t('user.type.title')" prop="userCustomerId">
              <template #default="scope">
                <div>{{ roleMap?.get(scope.row.roleIds) }}</div>
                <!--<el-tag v-if="scope.row.userCustomerId === 0">
                  {{ t("user.type.0") }}
                </el-tag>
                <el-tag v-else-if="scope.row.userType === 1">
                  {{ t("user.userTypeOptions.1") }}
                </el-tag>
                <el-tag v-else-if="scope.row.userType === 2">
                  {{ t("user.userTypeOptions.2") }}
                </el-tag>
                <el-tag v-else type="success">{{ t("user.type.1") }}</el-tag>-->
                <el-tooltip
                  placement="top-start"
                  effect="light"
                  :raw-content="true"
                  :disabled="
                    scope.row.regionNames != null && scope.row.regionNames.length > 2 ? false : true
                  "
                >
                  <template #content>
                    <div v-for="item in scope.row.regionNames.slice(1) || []">
                      <el-tag type="warning">
                        {{ item.split("-p")[0] }}
                      </el-tag>
                    </div>
                  </template>
                  <div>
                    <el-tag
                      v-for="item in scope.row.regionNames.slice(0, 3) || []"
                      v-if="scope.row.regionNames != null"
                      :key="item"
                      :type="item.includes('-p') ? 'primary' : 'warning'"
                    >
                      {{ item.split("-p")[0] }}
                    </el-tag>
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('common.showStatus')"
              align="center"
              prop="userStatus"
              width="80"
            >
              <template #default="scope">
                <el-tag v-if="scope.row.userStatus === 5" type="warning">
                  {{ $t("common.status.noAuth") }}
                </el-tag>
                <el-tag v-else-if="scope.row.userStatus === 10" type="success">
                  {{ $t("common.status.enable") }}
                </el-tag>
                <el-tag v-else-if="scope.row.userStatus === -1" type="danger">
                  {{ $t("common.status.disable") }}
                </el-tag>
                <el-tag v-else type="info">{{ $t("common.status.unEnable") }}</el-tag>
              </template>
            </el-table-column>
            <!--<el-table-column
              :label="$t('common.createdAt')"
              align="center"
              prop="createdAt"
              width="180"
            >
              <template #default="scope">
                {{ dayjs(scope.row.createdAt).format("YYYY-MM-DD HH:mm:ss") }}
              </template>
            </el-table-column>-->
            <el-table-column :label="$t('common.action')" fixed="right" width="220">
              <template #default="scope">
                <el-button
                  v-if="
                    (scope.row.userCustomerId > 0 && showEditDelete) ||
                    (scope.row.userCustomerId == 0 && !showEditDelete)
                  "
                  v-hasPerm="'sys:user:edit'"
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row.userId, 0)"
                >
                  {{ $t("common.edit") }}
                </el-button>
                <el-button
                  v-if="
                    (scope.row.userCustomerId > 0 && showEditDelete) ||
                    (scope.row.userCustomerId == 0 && !showEditDelete)
                  "
                  v-hasPerm="'sys:user:delete'"
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.userId)"
                >
                  {{ $t("common.delete") }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      @close="handleCloseDialog"
    >
      <el-form ref="userFormRef" :model="formData" :rules="rules">
        <el-form-item :label="$t('user.username')" prop="userEmail">
          <el-input
            v-model="formData.userEmail"
            :readonly="formData.userId ? true : false"
            :placeholder="
              $t('common.plsInput') + $t('user.username') + '(' + t('user.placeholderEmail') + ')'
            "
          />
        </el-form-item>

        <el-form-item :label="$t('user.fullName')" prop="userFullName">
          <el-input
            v-model="formData.userFullName"
            :placeholder="$t('common.plsInput') + $t('user.fullName')"
          />
        </el-form-item>
        <el-form-item v-if="showDept" :label="$t('common.dept')" prop="deptId">
          <el-select
            v-model="formData.deptId"
            :placeholder="$t('common.all')"
            :no-match-text="$t('common.all')"
            clearable
            class="!w-[100px]"
          >
            <el-option
              v-for="item in deptOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('user.phone')" prop="userPhone">
          <el-input
            v-model="formData.userPhone"
            :placeholder="$t('user.plsInputMobile')"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item :label="$t('user.password')" prop="userPassword">
          <el-input v-model="formData.userPassword" type="password" show-password placeholder="" />
        </el-form-item>
        <el-form-item :label="$t('common.showStatus')" prop="userStatus">
          <el-switch
            v-model="formData.userStatus"
            inline-prompt
            :active-text="$t('common.status.enable')"
            :inactive-text="$t('common.status.disable')"
            :active-value="10"
            :inactive-value="-1"
          />
        </el-form-item>
        <el-form-item :label="$t('user.role')" prop="roleIds">
          <el-select
            v-model="formData.roleIds"
            :placeholder="$t('common.choose')"
            :no-match-text="$t('common.choose')"
            @change="getRoleInfo"
          >
            <el-option
              v-for="item in roleOptions"
              :key="Number(item.value)"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="changeCustomerEmail" :label="$t('user.changeCustomerEmailToo')" prop="">
          <el-switch v-model="formData.changeCustomerEmailToo" />
        </el-form-item>
        <el-form-item
          v-if="showRegion"
          :label="$t('user.userMainManageRegion')"
          prop="customerRegionId"
        >
          <el-select
            v-model="formData.customerRegionId"
            style="width: 240px"
            :placeholder="$t('common.plsChoose') + $t('user.userManageRegion')"
            :no-match-text="$t('common.plsChoose') + $t('user.userManageRegion')"
            clearable
            class="!w-[100px]"
          >
            <el-option
              v-for="item in mainRegionList"
              :key="item.customerId"
              :label="item.customerName"
              :value="item.customerId"
              :disabled="(formData.customerRegionIds as any[])?.includes(item.customerId)"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formData.customerRegionId"
          :label="$t('user.userManageRegionOptions')"
          prop="customerRegionIds"
        >
          <el-select
            v-model="formData.customerRegionIds"
            style="width: 240px"
            :placeholder="$t('common.plsChoose') + $t('user.userManageRegion')"
            :no-match-text="$t('common.plsChoose') + $t('user.userManageRegion')"
            multiple
            clearable
            class="!w-[100px]"
          >
            <el-option
              v-for="item in regionList"
              :key="item.customerId"
              :label="item.customerName"
              :title="item.customerName"
              :value="item.customerId"
              :disabled="formData.customerRegionId == item.customerId"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="formData.userId" :label="$t('common.createdAt')" prop="createdAt">
          {{ formData.createdAt ? dayjs(formData.createdAt).format("YYYY-MM-DD HH:mm:ss") : "" }}
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmity">{{ $t("common.confirm") }}</el-button>
          <el-button v-if="showApply" type="success" @click="handleSubmitApply">
            {{ $t("common.keepAdd") }}
          </el-button>
          <el-button @click="handleCloseDialog">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import RoleAPI from "@/api/system/role";
import UserAPI, { UserForm, UserPageQuery, UserPageVO } from "@/api/system/user";
import RegionApi, { IForm, IPageQuery, IPageVO } from "@/api/system/region";
import DeptAPI from "@/api/dept/index";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
import { Arrayable } from "@vueuse/core";
import { FormItemRule } from "element-plus";
import CustomerAPI from "@/api/customer";
const { t } = useI18n();
defineOptions({
  name: "User",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);
const deptOptions = ref<OptionType[]>();
const showRegion = ref(false);
const showUserType = ref(false);
const showDept = ref(true);
const customerRegionUq = ref(0);
const changeCustomerEmail = ref(false);
const showTooltip = ref(false);
const showApply = ref(false);
const regionList = ref<
  {
    customerId: number;
    customerName: string;
  }[]
>([]);
const mainRegionList = ref<
  {
    customerId: number;
    customerName: string;
  }[]
>([]);

const queryParams = reactive<UserPageQuery>({
  pageNum: 1,
  pageSize: 10,
  userStatus: undefined,
  deptId: undefined,
  userType: 1,
  isAdmin: 0,
});

const roleOptions = ref<OptionType[]>();

const deptOptionsToName = ref<{
  [key: string]: string;
}>({});

const pageData = ref<UserPageVO[]>();
const total = ref(0);
const loading = ref(false);
const showEditDelete = ref(false);

const dialog = reactive({
  visible: false,
  title: t("common.add"),
});

const formData = reactive<UserForm>({
  userStatus: 10,
  userEmail: "",
  deptId: undefined,
  roleIds: undefined,
  changeCustomerEmailToo: false,
  userType: 1,
  customerRegionId: undefined,
  customerRegionIds: [],
  createdAt: "",
});

const rules: Partial<Record<keyof UserForm, Arrayable<FormItemRule>>> = {
  userEmail: [
    { required: true, message: t("common.plsInput") + t("user.username"), trigger: "blur" },
    {
      type: "email",
      message: t("common.plsInput") + t("user.placeholderEmail"),
      trigger: "blur",
    },
  ],
  userFullName: [
    { required: true, message: t("common.plsInput") + t("user.fullName"), trigger: "blur" },
  ],
  roleIds: [{ required: true, message: t("common.plsChoose") + t("role.name"), trigger: "blur" }],
  //deptId: [{ required: true, message: t("common.choose") + t("common.dept"), trigger: "blur" }],
};

const selectIds = ref<number[]>([]);

function handleQuery() {
  loading.value = true;
  UserAPI.getPage(queryParams)
    .then((data) => {
      const lists = [];
      if (data.list != null) {
        for (const item of data.list) {
          lists.push(item);
        }
      }
      pageData.value = lists;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.createdAt = undefined;
  handleQuery();
}

function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.userId);
}

const keepAdd = ref(false);

async function handleOpenDialog(id?: number, type?: number) {
  dialog.visible = true;
  formData.changeCustomerEmailToo = false;
  changeCustomerEmail.value = false;
  if (type == 1) {
    keepAdd.value = true;
  }
  if (id) {
    showApply.value = false;
    dialog.title = t("common.edit");
    UserAPI.getFormData(id).then((data) => {
      Object.assign(formData, { ...data });
      getMainRegions(id);
      if (formData.customerRegionId == 0) {
        formData.customerRegionId = undefined;
      }
      if (formData.deptId == 0) {
        formData.deptId = undefined;
      }
      if (
        data.customerRegionIds != null &&
        typeof data.customerRegionIds === "string" &&
        data.customerRegionIds !== ""
      ) {
        formData.customerRegionIds = data.customerRegionIds
          .split(",")
          .map((item) => parseInt(item));
      }
      RoleAPI.getFormData(formData.roleIds).then((res) => {
        if (res.userType == 2) {
          showRegion.value = true;
          formData.userType = 2;
        } else if (res.userType == 10) {
          formData.userType = 10;
          //changeCustomerEmail.value = true;
        }
      });
    });
  } else {
    showApply.value = true;
    dialog.title = t("common.add");
    getMainRegions(0);
  }

  function getMainRegions(userId: number) {
    if (customerRegionUq.value === 0) {
      let mainRegionIdsByOtherUsers = [];
      UserAPI.getRegionIdsByOtherUser(userId).then((res) => {
        if (res != null) {
          for (const item of res) {
            mainRegionIdsByOtherUsers.push(item.customerRegionId);
          }
        }
        mainRegionList.value = regionList.value.filter(
          (item) => !mainRegionIdsByOtherUsers.includes(item.customerId)
        );
      });
    } else {
      mainRegionList.value = regionList.value;
    }
  }

  UserAPI.getProfile().then((res) => {
    if (res.isAdmin === 1) {
      showUserType.value = true;
    } else {
      showUserType.value = false;
    }

    if (res.userCustomerId === 0) {
      showDept.value = false;
    }
  });
}

function handleCloseDialog() {
  dialog.visible = false;
  keepAdd.value = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.userId = undefined;
  formData.userStatus = 1;
  formData.userFullName = undefined;
  formData.changeCustomerEmailToo = false;
}
function handleSubmity() {
  keepAdd.value = false;
  handleSubmit();
}

function handleSubmitApply() {
  keepAdd.value = true;
  handleSubmit();
}

const handleSubmit = () => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.userId;
      loading.value = true;
      if (Array.isArray(formData.customerRegionIds)) {
        formData.customerRegionIds = formData.customerRegionIds.join(",");
      } else {
        formData.customerRegionIds = "";
      }
      if (userId) {
        if (formData.userPassword && formData.userPassword.length < 6) {
          ElMessage.error(t("profile.passwdLength"));
          loading.value = false;
          return;
        }
        UserAPI.update(userId, formData)
          .then((res) => {
            if (res.data.code === 200) {
              ElMessage.success(res.data.message);
              handleCloseDialog();
              handleResetQuery();
            } else {
              ElMessage.error(res.data.message);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        if (!formData.userPassword || formData.userPassword.length < 6) {
          ElMessage.error(t("profile.passwdLength"));
          loading.value = false;
          return;
        }
        UserAPI.add(formData)
          .then((res) => {
            if (res.data.code === 200) {
              ElMessage.success(res.data.message);
              if (keepAdd.value) {
                handleResetForm();
              } else {
                handleCloseDialog();
              }
              handleResetQuery();
            } else {
              ElMessage.error(res.data.message);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
};

function handleResetForm() {
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.userId = undefined;
  formData.userStatus = 1;
  formData.userFullName = undefined;
  formData.changeCustomerEmailToo = false;
}

function handleDelete(userId?: number) {
  const userIds = [userId || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning(t("common.plsChooseDeleteItem"));
    return;
  }

  ElMessageBox.confirm(t("common.confirmDelete"), t("common.warning"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      UserAPI.deleteByIds(userIds)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            handleResetQuery();
          } else {
            ElMessage.error(res.data.message);
          }
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info(t("common.cancelDelete"));
    }
  );
}

function getDeptOptions() {
  console.log("getDeptOptions");
  DeptAPI.getList({
    pageNum: 1,
    pageSize: 100,
  })
    .then((res) => {
      let options = [];
      let idToName: { [key: number]: string } = {};
      for (let i = 0; i < res.list.length; i++) {
        options.push({
          value: res.list[i].id,
          label: res.list[i].name,
        });
        idToName[res.list[i].id] = res.list[i].name;
      }
      deptOptionsToName.value = idToName;
      deptOptions.value = options;
    })
    .finally(() => {
      loading.value = false;
    });
}

function getRegionList() {
  RegionApi.getList({
    pageNum: 1,
    pageSize: 10000,
  })
    .then((res) => {
      regionList.value = res.list;

      CustomerAPI.getCurrentLogedUsersCustomer().then((res) => {
        customerRegionUq.value = res.mainRegionuq;
      });
    })
    .finally(() => {
      loading.value = false;
    });
}

watch(
  () => formData.userType,
  (newTargetData, oldTargetData) => {
    if (newTargetData === 2) {
      showRegion.value = true;
    } else {
      showRegion.value = false;
      formData.customerRegionId = 0;
    }
  },
  { deep: true }
);

watch(
  () => formData.customerRegionId,
  (newTargetData, oldTargetData) => {
    if (newTargetData === 0 || newTargetData === undefined) {
      formData.customerRegionIds = [];
    }
  },
  { deep: true }
);

function getRoleInfo() {
  RoleAPI.getFormData(formData.roleIds).then((res) => {
    if (res.userType == 2) {
      showRegion.value = true;
      formData.userType = 2;
    } else if (res.userType == 10) {
      formData.userType = 10;
      changeCustomerEmail.value = true;
    } else {
      showRegion.value = false;
      formData.userType = 1;
      formData.customerRegionId = 0;
      formData.customerRegionIds = [];
    }
  });
}

const roleMap = ref<Map<any, string>>();

async function getRoleOptions() {
  roleOptions.value = await RoleAPI.getRoleOptions();
  const map = new Map<any, string>();
  for (let i = 0; i < roleOptions.value.length; i++) {
    map.set(roleOptions.value[i].value, roleOptions.value[i].label);
  }
}

async function getAllRoleOptions() {
  const roles = await RoleAPI.findAllRoles();
  const map = new Map<any, string>();
  for (let i = 0; i < roles.length; i++) {
    map.set(roles[i].roleId, roles[i].roleName ?? "");
  }
  roleMap.value = map;
}

function profile() {
  UserAPI.getProfile().then((res) => {
    if (res.userCustomerId > 0) {
      showEditDelete.value = true;
    }
  });
}

onMounted(() => {
  profile();
  getAllRoleOptions();
  getRoleOptions();
  getDeptOptions();
  handleQuery();
  getRegionList();
});

const displayCustomerRegionId = computed({
  get: () => {
    return formData.customerRegionId === 0 ? null : formData.customerRegionId;
  },
  set: (value: number | null) => {
    formData.customerRegionId = value ?? 0;
  },
});
</script>
